const tbody = document.querySelector('tbody')


getScore()

tbody.addEventListener('dblclick', function (e) {
  //双击的范围 是td标签，而且有score类名
  let td = e.target
  if (td.classList.contains('score') && td.tagName === 'TD') {

    const input = td.querySelector('input')
    //显示输入框
    input.style.display = 'block'

    //获得焦点
    input.focus()
    input.value = td.innerText

  }
})




//#region 函数 获取input 绑定 失去焦点事件  其他标签没用，不适用tbody委托
function inputAddBlur() {
  const inputs = tbody.querySelectorAll('input')
  inputs.forEach(input => {


    input.addEventListener('blur', function () {
      //获取三个数据 stu_id batch score

      const {
        stu_id,
        batch
      } = this.dataset

      //前端限制分数区间
      // const score = this.value <= 100 && this.value >= 0 ? this.value : valueInit
      const score = this.value
      if (score >= 0 && score <= 100) {
        axios.post('/score/entry', {
          stu_id,
          batch,
          score
        }).then(result => {
          if (result.data.code === 0) {
            toastr.success(result.data.message)
          }
          getScore()
        })
      } else {
        toastr.error('请输入0~100的数字')
      }
      this.style.display = 'none'
    })
  })
}
//#endregion



function getScore() {
  axios.get('/score/list').then(result => {
    let data = result.data.data
    let html = ``
    for (let key in data) {
      html += `
      <tr>
        <th scope="row">${key}</th>
        <td>${data[key].name}</td>
        <td class="score">${data[key].score[0]} <input data-stu_id="${key}" data-batch="${1}" type="text" /></td>
        <td class="score">${data[key].score[1]} <input data-stu_id="${key}" data-batch="${2}" type="text" /></td>
        <td class="score">${data[key].score[2]} <input data-stu_id="${key}" data-batch="${3}" type="text" /></td>
        <td class="score">${data[key].score[3]} <input data-stu_id="${key}" data-batch="${4}" type="text" /></td>
        <td class="score">${data[key].score[4]} <input data-stu_id="${key}" data-batch="${5}" type="text" /></td>
      </tr>`

    }
    tbody.innerHTML = html
    inputAddBlur()
  })
}